<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>我的申请</span>
      </div>
    </template>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      stripe
    >
      <el-table-column label="学年" align="center" header-align="center" width="130">
        <template #default="scope">
          {{ formatAcademicYear(scope.row.academicYear) }}
        </template>
      </el-table-column>
      <el-table-column label="困难等级" align="center" header-align="center" width="110">
        <template #default="scope">
          <el-tag v-if="scope.row.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" header-align="center" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">拒绝</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">辅导员审核</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning">学院审核</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="warning">学校审核</el-tag>
          <el-tag v-else-if="scope.row.status === 4" type="success">通过</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" align="center" header-align="center" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.applyTime) }}
        </template>
      </el-table-column>
      <el-table-column label="申请理由" align="center" header-align="center" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.applyReason || '无' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)">查看详情</el-button>
          <el-button 
            v-if="scope.row.status === 4" 
            link 
            type="success" 
            @click="handleRegister(scope.row)"
          >
            登记
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="queryParams.page"
      :page-size="queryParams.limit"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      @update:current-page="(val) => queryParams.page = val"
      @update:page-size="(val) => queryParams.limit = val"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 登记对话框 -->
    <el-dialog 
      v-model="registerVisible" 
      title="衣服登记" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        v-loading="registerLoading"
        label-width="120px"
      >
        <el-form-item label="选择款式">
          <el-radio-group 
            v-model="registrationForm.styleId" 
            @change="handleStyleChange"
            class="style-radio-group"
          >
            <el-radio 
              v-for="style in filteredClothingStyles" 
              :key="style.id" 
              :label="style.id"
              border
              class="style-radio-item"
            >
              <div class="style-item-content">
                <el-image 
                  v-if="style.image" 
                  :src="style.image" 
                  fit="cover"
                  class="style-image"
                  :preview-src-list="[style.image]"
                />
                <div v-else class="style-image-placeholder">暂无图片</div>
                <div class="style-name">{{ style.name }}</div>
                <el-tag 
                  size="small" 
                  :type="style.genderLimit === 0 ? 'danger' : style.genderLimit === 1 ? 'primary' : 'info'"
                >
                  {{ style.genderLimit === 0 ? '女款' : style.genderLimit === 1 ? '男款' : '通用' }}
                </el-tag>
              </div>
            </el-radio>
          </el-radio-group>
          <el-empty 
            v-if="!registerLoading && filteredClothingStyles.length === 0" 
            description="暂无可选款式" 
            :image-size="100"
          />
        </el-form-item>

        <el-form-item label="选择尺码" v-if="sizeList.length > 0">
          <el-radio-group v-model="registrationForm.sizeId">
            <el-radio 
              v-for="size in sizeList" 
              :key="size.id" 
              :label="size.id"
              border
            >
              <div class="size-item-content">
                <strong>{{ size.size }}</strong>
                <span v-if="size.description" class="size-description">
                  （{{ size.description }}）
                </span>
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitRegister"
          :loading="registerLoading"
        >
          确认登记
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="申请详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学年">
          {{ formatAcademicYear(detailData.academicYear) }}
        </el-descriptions-item>
        <el-descriptions-item label="困难等级">
          <el-tag v-if="detailData.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag v-if="detailData.status === 0" type="danger">拒绝</el-tag>
          <el-tag v-else-if="detailData.status === 1" type="warning">辅导员审核</el-tag>
          <el-tag v-else-if="detailData.status === 2" type="warning">学院审核</el-tag>
          <el-tag v-else-if="detailData.status === 3" type="warning">学校审核</el-tag>
          <el-tag v-else-if="detailData.status === 4" type="success">通过</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ formatDateTime(detailData.applyTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(detailData.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请理由" :span="2">
          <div class="reason-text">{{ detailData.applyReason || '无' }}</div>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailData.rejectedReason" label="拒绝原因" :span="2">
          <div class="reason-text rejected">{{ detailData.rejectedReason }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { _getMyApplication, _getStudentByUserId } from '@/api/application'
import { _getListByBatchId, _getClothingStyleById } from '@/api/clothingStyle'
import { _saveRegistration } from '@/api/registration'
import { _getCurrentUser } from '@/api/user'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const detailVisible = ref(false)
const detailData = ref({})

// 登记相关数据
const registerVisible = ref(false)
const registerLoading = ref(false)
const currentApplication = ref(null)
const studentGender = ref(null)
const clothingStyleList = ref([])
const selectedStyle = ref(null)
const sizeList = ref([])
const registrationForm = reactive({
  styleId: null,
  sizeId: null
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10
})

// 格式化学年
const formatAcademicYear = (year) => {
  if (!year) return '-'
  return `${year}学年`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 查询列表
const getList = () => {
  loading.value = true
  _getMyApplication(queryParams).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch(err => {
    console.error('查询失败:', err)
    ElMessage.error('查询失败')
  }).finally(() => {
    loading.value = false
  })
}

// 查看详情
const handleDetail = (row) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

// 根据学生性别过滤衣服款式
const filteredClothingStyles = computed(() => {
  if (!clothingStyleList.value || clothingStyleList.value.length === 0) return []
  if (studentGender.value === null) return clothingStyleList.value
  
  // 过滤：genderLimit === 学生性别 || genderLimit === 2（通用）
  return clothingStyleList.value.filter(style => {
    return style.genderLimit === studentGender.value || style.genderLimit === 2
  })
})

// 点击登记按钮
const handleRegister = async (row) => {
  currentApplication.value = row
  registerVisible.value = true
  registerLoading.value = true
  
  // 重置表单
  registrationForm.styleId = null
  registrationForm.sizeId = null
  selectedStyle.value = null
  sizeList.value = []
  
  try {
    // 获取当前用户信息和学生信息
    const userRes = await _getCurrentUser()
    if (userRes && userRes.code === 200) {
      const userId = userRes.data.user.id
      const studentRes = await _getStudentByUserId(userId)
      if (studentRes && studentRes.code === 200) {
        studentGender.value = studentRes.data.student.gender
      }
    }
    
    // 根据批次ID获取衣服列表
    const res = await _getListByBatchId(row.batchId)
    if (res && res.code === 200) {
      clothingStyleList.value = res.data.clothingStyleList || []
    } else {
      ElMessage.error(res.message || '获取衣服信息失败')
    }
  } catch (error) {
    console.error('获取衣服信息失败:', error)
    ElMessage.error('获取衣服信息失败')
  } finally {
    registerLoading.value = false
  }
}

// 选择款式时获取尺码列表
const handleStyleChange = async (styleId) => {
  if (!styleId) {
    sizeList.value = []
    registrationForm.sizeId = null
    return
  }
  
  try {
    const res = await _getClothingStyleById(styleId)
    if (res && res.code === 200) {
      sizeList.value = res.data.clothingStyle.sizes || []
      registrationForm.sizeId = null
      selectedStyle.value = res.data.clothingStyle
    } else {
      ElMessage.error(res.message || '获取尺码信息失败')
    }
  } catch (error) {
    console.error('获取尺码信息失败:', error)
    ElMessage.error('获取尺码信息失败')
  }
}

// 提交登记
const handleSubmitRegister = async () => {
  if (!registrationForm.styleId) {
    ElMessage.warning('请选择衣服款式')
    return
  }
  if (!registrationForm.sizeId) {
    ElMessage.warning('请选择尺码')
    return
  }
  
  try {
    await ElMessageBox.confirm('确认提交登记信息吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    registerLoading.value = true
    
    const registrationData = {
      applicationId: currentApplication.value.id,
      styleId: registrationForm.styleId,
      sizeId: registrationForm.sizeId
    }
    
    const res = await _saveRegistration(registrationData)
    if (res && res.code === 200) {
      ElMessage.success('登记成功')
      registerVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '登记失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('登记失败:', error)
      ElMessage.error('登记失败')
    }
  } finally {
    registerLoading.value = false
  }
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.page = page
  getList()
}

const handleSizeChange = (size) => {
  queryParams.limit = size
  queryParams.page = 1
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 18px;
    font-weight: bold;
  }
}

.reason-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  
  &.rejected {
    color: #f56c6c;
  }
}

// 登记对话框样式
.style-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.style-radio-item {
  margin: 0 !important;
  height: auto !important;
  
  :deep(.el-radio__label) {
    padding: 0;
  }
}

.style-item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  min-width: 150px;
  
  .style-image {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    cursor: pointer;
  }
  
  .style-image-placeholder {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 14px;
  }
  
  .style-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    text-align: center;
  }
}

.size-item-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  
  .size-description {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }
}
</style>
